package com.alibaba.langengine.jsonrepair.examples;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.langengine.jsonrepair.JsonRepair;
import com.alibaba.langengine.jsonrepair.JsonSafeParser;

/**
 * JsonRepairExamples - Comprehensive examples of using JsonRepair and JsonSafeParser
 * 
 * This class provides examples of how to use the JsonRepair and JsonSafeParser utilities
 * to handle various types of malformed JSON that are commonly generated by Large Language Models.
 * Each method demonstrates a specific error case and how to handle it.
 */
public class JsonRepairExamples {
    
    /**
     * Main method to run all examples
     */
    public static void main(String[] args) {
        System.out.println("=== Running JsonRepair and JsonSafeParser Examples ===\n");
        
        // Run all examples
        exampleMissingQuotesAroundKeys();
        exampleMissingCommas();
        exampleTrailingCommas();
        exampleCommentsInJson();
        exampleSingleQuotes();
        exampleUnbalancedBrackets();
        exampleTypeMismatch();
        exampleComplexNestedJson();
        exampleJsonSafeParserBasicUsage();
    }
    
    /**
     * Example 1: Missing quotes around keys
     * 
     * This example demonstrates how to handle JSON with missing quotes around keys,
     * which is a common error in LLM-generated JSON.
     */
    public static void exampleMissingQuotesAroundKeys() {
        System.out.println("=== Example 1: Missing quotes around keys ===");
        
        // Malformed JSON with missing quotes around keys
        String malformedJson = "{ name: \"John\", age: 30 }";
        System.out.println("Original JSON: " + malformedJson);

        try {
            // This will fail with FastJSON
            Object parsed = JSON.parseObject(malformedJson);
            System.out.println("Parsed with FastJSON: " + parsed);
        } catch (JSONException e) {
            System.out.println("FastJSON failed to parse: " + e.getMessage());
            
            // Use JsonRepair instead
            Object repaired = JsonRepair.loads(malformedJson);
            System.out.println("Repaired and parsed: " + repaired);
            
            // Get the repaired JSON string
            String repairedJson = JsonRepair.repairJson(malformedJson);
            System.out.println("Repaired JSON: " + repairedJson);
            
            // Parse the repaired JSON
            JSONObject jsonObject = JSON.parseObject(repairedJson);
            System.out.println("Accessing name field: " + jsonObject.getString("name"));
        }
        
        System.out.println("\n");
    }
    
    /**
     * Example 2: Missing commas between elements
     * 
     * This example demonstrates how to handle JSON with missing commas between elements,
     * which is a common error in LLM-generated JSON.
     */
    public static void exampleMissingCommas() {
        System.out.println("=== Example 2: Missing commas between elements ===");
        
        // Malformed JSON with missing commas
        String malformedJson = "{ \"name\": \"John\" \"age\": 30 \"city\": \"New York\" }";
        System.out.println("Original JSON: " + malformedJson);

        try {
            // This will fail with FastJSON
            Object parsed = JSON.parseObject(malformedJson);
            System.out.println("Parsed with FastJSON: " + parsed);
        } catch (JSONException e) {
            System.out.println("FastJSON failed to parse: " + e.getMessage());
            
            // Use JsonRepair instead
            Object repaired = JsonRepair.loads(malformedJson);
            System.out.println("Repaired and parsed: " + repaired);
            
            // Get the repaired JSON string
            String repairedJson = JsonRepair.repairJson(malformedJson);
            System.out.println("Repaired JSON: " + repairedJson);
            
            // Alternatively, use JsonSafeParser
            JSONObject safeResult = JsonSafeParser.parseObject(malformedJson);
            System.out.println("JsonSafeParser result: " + safeResult);
        }
        
        System.out.println("\n");
    }
    
    /**
     * Example 3: Trailing commas in arrays and objects
     * 
     * This example demonstrates how to handle JSON with trailing commas,
     * which is a common error in LLM-generated JSON.
     */
    public static void exampleTrailingCommas() {
        System.out.println("=== Example 3: Trailing commas in arrays and objects ===");
        
        // Malformed JSON with trailing commas
        String malformedJson = "{ \"items\": [1, 2, 3, ], \"settings\": { \"active\": true, } }";
        System.out.println("Original JSON: " + malformedJson);

        try {
            // This will fail with FastJSON
            Object parsed = JSON.parseObject(malformedJson);
            System.out.println("Parsed with FastJSON: " + parsed);
        } catch (JSONException e) {
            System.out.println("FastJSON failed to parse: " + e.getMessage());
            
            // Use JsonRepair instead
            Object repaired = JsonRepair.loads(malformedJson);
            System.out.println("Repaired and parsed: " + repaired);
            
            // Get the repaired JSON string
            String repairedJson = JsonRepair.repairJson(malformedJson);
            System.out.println("Repaired JSON: " + repairedJson);
            
            // Parse the repaired JSON
            JSONObject jsonObject = JSON.parseObject(repairedJson);
            System.out.println("Accessing items array: " + jsonObject.getJSONArray("items"));
        }
        
        System.out.println("\n");
    }
    
    /**
     * Example 4: Comments in JSON
     * 
     * This example demonstrates how to handle JSON with comments,
     * which is not valid in standard JSON but often included in LLM outputs.
     */
    public static void exampleCommentsInJson() {
        System.out.println("=== Example 4: Comments in JSON ===");
        
        // Malformed JSON with comments
        String malformedJson = "{ \n" +
                              "  \"name\": \"John\", // This is a comment\n" +
                              "  /* This is a block comment */\n" +
                              "  \"age\": 30\n" +
                              "}";
        System.out.println("Original JSON: " + malformedJson);

        try {
            // This will fail with FastJSON
            Object parsed = JSON.parseObject(malformedJson);
            System.out.println("Parsed with FastJSON: " + parsed);
        } catch (JSONException e) {
            System.out.println("FastJSON failed to parse: " + e.getMessage());
            
            // Use JsonRepair instead
            Object repaired = JsonRepair.loads(malformedJson);
            System.out.println("Repaired and parsed: " + repaired);
            
            // Get the repaired JSON string
            String repairedJson = JsonRepair.repairJson(malformedJson);
            System.out.println("Repaired JSON: " + repairedJson);
            
            // Alternatively, use JsonSafeParser
            String validJson = JsonSafeParser.getValidJsonString(malformedJson);
            System.out.println("JsonSafeParser result: " + validJson);
        }
        
        System.out.println("\n");
    }
    
    /**
     * Example 5: Single quotes instead of double quotes
     * 
     * This example demonstrates how to handle JSON with single quotes,
     * which is not valid in standard JSON but often used by LLMs.
     */
    public static void exampleSingleQuotes() {
        System.out.println("=== Example 5: Single quotes instead of double quotes ===");
        
        // Malformed JSON with single quotes
        String malformedJson = "{ 'name': 'John', 'age': 30, 'skills': ['programming', 'design'] }";
        System.out.println("Original JSON: " + malformedJson);

        try {
            // This will fail with FastJSON
            Object parsed = JSON.parseObject(malformedJson);
            System.out.println("Parsed with FastJSON: " + parsed);
        } catch (JSONException e) {
            System.out.println("FastJSON failed to parse: " + e.getMessage());
            
            // Use JsonRepair instead
            Object repaired = JsonRepair.loads(malformedJson);
            System.out.println("Repaired and parsed: " + repaired);
            
            // Get the repaired JSON string
            String repairedJson = JsonRepair.repairJson(malformedJson);
            System.out.println("Repaired JSON: " + repairedJson);
            
            // Parse the repaired JSON
            JSONObject jsonObject = JSON.parseObject(repairedJson);
            System.out.println("Accessing skills array: " + jsonObject.getJSONArray("skills"));
        }
        
        System.out.println("\n");
    }
    
    /**
     * Example 6: Unbalanced brackets
     * 
     * This example demonstrates how to handle JSON with unbalanced brackets,
     * which is a common error in LLM-generated JSON.
     */
    public static void exampleUnbalancedBrackets() {
        System.out.println("=== Example 6: Unbalanced brackets ===");
        
        // Malformed JSON with unbalanced brackets
        String malformedJson = "{ \"name\": \"John\", \"items\": [1, 2, 3 }";
        System.out.println("Original JSON: " + malformedJson);

        try {
            // This will fail with FastJSON
            Object parsed = JSON.parseObject(malformedJson);
            System.out.println("Parsed with FastJSON: " + parsed);
        } catch (JSONException e) {
            System.out.println("FastJSON failed to parse: " + e.getMessage());
            
            // Use JsonSafeParser
            JSONObject safeResult = JsonSafeParser.parseObject(malformedJson);
            System.out.println("JsonSafeParser result: " + safeResult);
            
            // Get a valid JSON string
            String validJson = JsonSafeParser.getValidJsonString(malformedJson);
            System.out.println("Valid JSON string: " + validJson);
        }
        
        System.out.println("\n");
    }
    
    /**
     * Example 7: Type mismatch (object vs array)
     * 
     * This example demonstrates how to handle JSON with type mismatches,
     * which can occur when LLMs generate inconsistent JSON structures.
     */
    public static void exampleTypeMismatch() {
        System.out.println("=== Example 7: Type mismatch (object vs array) ===");
        
        // Case 1: JSON starts with { but should be an array
        String malformedJson1 = "{ \"items\": [{\"id\": 1}, {\"id\": 2}]";
        System.out.println("Original JSON (object with missing closing bracket): " + malformedJson1);
        
        // Use JsonSafeParser to get a valid JSON string
        String validJson1 = JsonSafeParser.getValidJsonString(malformedJson1);
        System.out.println("Valid JSON string: " + validJson1);
        
        // Case 2: JSON starts with [ but should be an object
        String malformedJson2 = "[{\"name\": \"John\", \"age\": 30}";
        System.out.println("\nOriginal JSON (array with missing closing bracket): " + malformedJson2);
        
        // Try to parse as array
        JSONArray array = JsonSafeParser.parseArray(malformedJson2);
        System.out.println("JsonSafeParser array result: " + array);
        
        // Get a valid JSON string
        String validJson2 = JsonSafeParser.getValidJsonString(malformedJson2);
        System.out.println("Valid JSON string: " + validJson2);
        
        System.out.println("\n");
    }
    
    /**
     * Example 8: Complex nested JSON with errors
     * 
     * This example demonstrates how to handle complex nested JSON with multiple errors,
     * which is common in real-world LLM outputs.
     */
    public static void exampleComplexNestedJson() {
        System.out.println("=== Example 8: Complex nested JSON with errors ===");
        
        // Complex malformed JSON with multiple issues
        String malformedJson = "{\n" +
                              "  'user': {\n" +
                              "    name: 'John Doe',\n" +
                              "    'age': 30,\n" +
                              "    'contact': {\n" +
                              "      'email': 'john@example.com'\n" +
                              "      'phone': '123-456-7890',\n" +
                              "    },\n" +
                              "    'skills': ['JavaScript', 'Python', 'Java',],\n" +
                              "    // User joined last year\n" +
                              "    'joined': '2022-01-01'\n" +
                              "  }\n" +
                              "}";
        System.out.println("Original complex JSON with multiple issues:");
        System.out.println(malformedJson);

        try {
            // This will fail with FastJSON
            Object parsed = JSON.parseObject(malformedJson);
            System.out.println("Parsed with FastJSON: " + parsed);
        } catch (JSONException e) {
            System.out.println("FastJSON failed to parse: " + e.getMessage());
            
            // Use JsonSafeParser
            JSONObject safeResult = JsonSafeParser.parseObject(malformedJson);
            System.out.println("JsonSafeParser result: " + safeResult);
            
            // Access nested properties to verify repair worked
            if (safeResult.containsKey("user")) {
                JSONObject user = safeResult.getJSONObject("user");
                System.out.println("User name: " + user.getString("name"));
                System.out.println("User skills: " + user.getJSONArray("skills"));
                
                if (user.containsKey("contact")) {
                    JSONObject contact = user.getJSONObject("contact");
                    System.out.println("User email: " + contact.getString("email"));
                }
            }
        }
        
        System.out.println("\n");
    }
    
    /**
     * Example 9: Basic usage of JsonSafeParser
     * 
     * This example demonstrates the basic usage patterns of JsonSafeParser
     * for handling potentially malformed JSON.
     */
    public static void exampleJsonSafeParserBasicUsage() {
        System.out.println("=== Example 9: Basic usage of JsonSafeParser ===");
        
        // Example JSON with various issues
        String testJson = "{\"request_id\":\"1234\",\"query\":{\"data\":[{\"id\":1}, {\"id\":2}],\"status\":\"ok\",}}";
        System.out.println("Test JSON: " + testJson);
        
        // 1. Parse as JSONObject
        System.out.println("\n1. Parse as JSONObject:");
        JSONObject obj = JsonSafeParser.parseObject(testJson);
        System.out.println("parseObject result keys: " + obj.keySet());
        
        // 2. Get valid JSON string
        System.out.println("\n2. Get valid JSON string:");
        String validJson = JsonSafeParser.getValidJsonString(testJson);
        System.out.println("Valid JSON: " + validJson);
        
        // 3. Verify the result can be parsed
        System.out.println("\n3. Verify parsing of repaired JSON:");
        try {
            JSONObject verifyParse = JSON.parseObject(validJson);
            System.out.println("Verification successful, keys: " + verifyParse.keySet());
        } catch (Exception e) {
            System.out.println("Verification failed: " + e.getMessage());
        }
        
        // 4. Example with array
        System.out.println("\n4. Example with JSON array:");
        String arrayJson = "[{\"name\":\"John\"}, {\"name\":\"Jane\",}]";
        JSONArray array = JsonSafeParser.parseArray(arrayJson);
        System.out.println("parseArray result size: " + array.size());
        
        System.out.println("\n");
    }
}
